package com.imay.live.proto.helper;


import com.alibaba.fastjson.JSON;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.ThreadManager;
import com.imay.live.proto.ProtoError;
import com.imay.live.proto.ResultCode;
import com.imay.tbas_api.IMYTBASObject;

/**
 * Created by jeaman on 2017/4/12.
 */

public class ProtoRequest {
    private IMYTBASObject mRequest;
    private int mTag;
    private int mType;   //HTTP请求

    private final int NET_ERROR = 10001;

    private final int NO_NETWORK = 0;

    public ProtoRequest(int type) {
        mType = type;
        mRequest = new IMYTBASObject();
    }

    public ProtoRequest setTag(int tag) {
        mTag = tag;
        return this;
    }

    public int getTag() {
        return mTag;
    }

    public void setCommand(String command) {
        mRequest.stringCommand = command;
    }

    public void setData(String data) {
        mRequest.stringData = data;
    }

    public String request(final ProtoCallBack protoCallBack) {
        return request(protoCallBack, true);
    }

    public String request(final ProtoCallBack protoCallBack, final boolean mainThreadCallBack) {
        if (mTag == 0 && protoCallBack != null) {
            setTag(protoCallBack.hashCode());
        }
        mRequest.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject object) {
                ProtoRequestHelper.removeRequest(ProtoRequest.this);//从队列移除
                if (protoCallBack == null) {
                    return;
                }
                final String stringCommand = object.stringCommand;
                if (object.errorNumber == 0) {
                    final boolean success;
                    final String data;
                    final int errorCode;
                    final String errorMessage;
                    if (mType == ProtoFactory.REQUEST_TYPE_HTTP) { //http
                        if (object.http_timed_out || object.http_error != 0 || object.http_status_code != 200) {
                            success = false;
                            data = null;
                            errorCode = (object.http_status_code != 200 && object.http_status_code != NO_NETWORK) ? -object.http_status_code : NET_ERROR;    //无网络或者网络超时
                            errorMessage = null;
                        } else if (object.http_type == ProtoFactory.HTTP_TYPE_DOWNLOAD) { //下载
                            success = true;
                            data = object.http_local_file;
                            errorCode = 0;
                            errorMessage = null;
                        } else {
                            ProtoError protoError = null;
                            try {
                                protoError = JSON.parseObject(object.http_data, ProtoError.class);
                            } catch (Throwable e) {
                                e.printStackTrace();
                            }
                            if (protoError != null) {
                                success = protoError.result == ResultCode.CodeSuccess;
                                errorCode = protoError.result;
                                errorMessage = protoError.errorDesc;
                                data = object.http_data;
                            } else {
                                success = false;
                                errorCode = -1; //数据解析错误
                                errorMessage = null;
                                data = null;
                            }
                        }
                    } else {    //socket
                        if (!object.socket_timed_out && !object.socket_disconnected) {
                            ProtoError protoError = null;
                            try {
                                protoError = JSON.parseObject(object.socket_content, ProtoError.class);
                            } catch (Throwable e) {
                                e.printStackTrace();
                            }
                            if (protoError != null) {
                                success = protoError.result == ResultCode.CodeSuccess;
                                data = object.socket_content;
                                errorCode = protoError.result;
                                errorMessage = protoError.errorDesc;
                            } else {
                                success = false;
                                data = null;
                                errorCode = -1; //数据解析错误
                                errorMessage = null;
                            }
                        } else {
                            success = false;
                            data = null;
                            errorCode = object.socket_disconnected ? NET_ERROR : 1;    //无网络或者网络超时
                            errorMessage = null;
                        }
                    }

                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            if (protoCallBack != null) {
                                try {   //防止数据错误导致的崩溃
                                    if (success) {
                                        protoCallBack.onRequestSuccess(stringCommand, data);
                                    } else {
                                        if(errorCode == ResultCode.CodeAccountUserNotLogin){
                                            EventHelper.postUserNoLogin();
                                        }
                                        if (errorCode==110){//适用于编辑资料敏感词检测
                                            protoCallBack.onRequestError(stringCommand, errorCode, data);
                                        }else{
                                            protoCallBack.onRequestError(stringCommand, errorCode, errorMessage);
                                        }
                                    }
                                } catch (Throwable e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    };
                    //是否通过主线程回调
                    if (mainThreadCallBack) {
                        ThreadManager.post(runnable);
                    } else {
                        runnable.run();
                    }
                } else {
                    final int errorCode = object.errorNumber;
                    final String message = object.stringError;
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            if (protoCallBack != null) {
                                protoCallBack.onRequestError(stringCommand, errorCode, message);
                            }
                        }
                    };

                    //是否通过主线程回调
                    if (mainThreadCallBack) {
                        ThreadManager.post(runnable);
                    } else {
                        runnable.run();
                    }
                }
            }
        });
        //通过子线程调用，防止阻塞主线程
        ThreadManager.post(ThreadManager.THREAD_NORMAL, new Runnable() {
            @Override
            public void run() {
                mRequest.asyncCommandWithTBASObject();
            }
        });
        return mRequest.stringCommand;
    }

    //返回全量数据（仅cocos使用）
    public String requestFullData(final ProtoSocketCallBack protoCallBack) {
        if (mTag == 0) {
            setTag(this.hashCode());
        }
        mRequest.setDataResultListener(new IMYTBASObject.OnDataResultListener() {
            @Override
            public void onCommandTaskSuccess(IMYTBASObject object) {
                ProtoRequestHelper.removeRequest(ProtoRequest.this);//从队列移除
                if (protoCallBack != null) {
                    protoCallBack.onRequestSuccess(object.stringCommand, object.socket_msg_id, object.socket_content);
                }
            }
        });
        mRequest.asyncCommandWithTBASObject();
        return mRequest.stringCommand;
    }

    public void destroy() {
        //通过子线程调用，防止阻塞主线程
        ThreadManager.post(ThreadManager.THREAD_NORMAL, new Runnable() {
            @Override
            public void run() {
                mRequest.destroy();
            }
        });
    }
}
